#!/bin/sh
set -x


echo **********************************Start********************************
date

# check version value 
echo $Version
# 检查版本号,如果版本号为0,提示错误，并退出
function checkVersion(){

	if [ "${Version}" -eq "0" ];then
    	echo "The current version number value is 0,exit 1"
        exit 1
    fi
}

checkVersion


cd ${WORKSPACE}/master
# 获取最近一次远程 master 提交的 commit id
sha1=`git rev-parse remotes/origin/master^{commit}`
# 获取姓名及邮箱，来配置git提交者信息
name=`git show --pretty=%an $sha1 | awk 'NR==1{print}'`
email=`git show --pretty=%ce $sha1 | awk 'NR==1{print}'`
echo '################# 当前提交人信息:'
echo $name 
echo $email 
git config --global user.name $name
git config --global user.email $email

# 获取 merge 的源分支前缀
function getOriginPrefix(){
  # 获取分支所属
  info_sha1=`git show $sha1 | grep 'Merge:' | cut -d' ' -f3`
  info_branch=`git branch -r --contains $info_sha1`
  # 判断是否 hotfix 分支
  isHotfix=`echo "${info_branch}" | grep 'origin/hotfix'`
  if [ -n "$isHotfix" ]; then 
    echo 'hotfix'
  else
    echo 'release'
  fi
}
originBra=$(getOriginPrefix)
echo '################# 获取的源分支前缀为:' $originBra
 


##检测版本号格式通过之后,根据构建时选择的动作执行封版或合代码动作
# 封版操作
echo ${Action}


remote="origin"
verBranch=${Version}
testBranch="test"

function createBranch(){

  echo "============Delete local and remote test branche========="
  echo "Removing local test branch..."
  git branch -d ${verBranch}
  git branch -d ${testBranch}
  
  echo "Removing remote test branch..."
  git push --delete $remote ${verBranch}
  git push --delete $remote ${testBranch}
  
  
  echo "Switching to verBranch local branch..."
  git checkout -b $verBranch
  git commit -a -m "add ${verBranch}"
  git push --set-upstream origin ${verBranch}
  
  
  echo "Creating test Branch..."
  git checkout -b $testBranch
  git commit -a -m "add ${testBranch}"
  git push --set-upstream origin ${testBranch}

}


function MergeVersion(){

  newBranch=${Version}
  echo "Merge $newBranch into test Branch..."
  git checkout $testBranch
  git merge origin/$newBranch || exit 1
  git push --set-upstream origin ${testBranch} || exit 1
  echo "Merge into test branch successful ..."

}


case $Action in
    CreateVersion)
    	createBranch
        ;;
    MergeVersion)
        MergeVersion
        ;;
esac